package com.zhou.common.pub.exception;

import com.google.common.collect.Lists;
import com.zhou.common.pub.enums.ResponseEnum;
import com.zhou.common.pub.model.Response;
import com.zhou.common.pub.properties.CommonProperties;
import com.zhou.common.pub.util.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@RestControllerAdvice
public class BaseExceptionHandler {


    private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private HttpServletRequest request;

    protected CommonProperties commonProperties;

    public BaseExceptionHandler(CommonProperties commonProperties) {
        this.commonProperties = commonProperties;
    }

    public BaseExceptionHandler() {
    }

    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        logger.error("", e);
        Response response;
        if (commonProperties != null && commonProperties.getPrintExceptionDetail()) {
            response = new Response(999,
                    StringUtils.isEmpty(e.getMessage()) ? e.getClass().toString() : e.getMessage());
        } else {
            response = Response.error();
        }
        logger.error("响应结果:{}", JSONUtils.toJson(response));
        return response;
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response handleException(HttpMessageNotReadableException e) {
        logger.error("", e);
        Response response = new Response(400, e.getMessage());
        logger.error("响应结果:{}", JSONUtils.toJson(response));
        return response;
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BizException.class)
    public Response<String> handleMessageException(BizException e) {
        logger.error(String.format("[%s] : %s,%s, ip : {}", request.getRequestURI(), e.getCode(), e.getMessage()),
                getIpAddress());
        Response response = new Response(e.getCode(), e.getMsg());
        logger.error("响应结果:{}", JSONUtils.toJson(response));
        return response;
    }


    @ExceptionHandler(DuplicateKeyException.class)
    public Response<String> handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(String.format("[%s] : %s, ip : {}", request.getRequestURI(), e.getMessage()),
                getIpAddress(), e);
        Response response = new Response(ResponseEnum.PARAM_ERROR.getCode(), ResponseEnum.PARAM_ERROR.getMsg(),
                e.getMessage());
        logger.error("响应结果:{}", JSONUtils.toJson(response));
        return response;
    }

    @ExceptionHandler({MethodArgumentNotValidException.class,
            BindException.class})
    public Response<String> handleArgumentException(BindException e) {

        BindingResult result = e.getBindingResult();

        List<FieldError> fieldErrors = result.getFieldErrors();

        List<ParamError> errors = Lists.newArrayList();
        fieldErrors.forEach(t -> {
            errors.add(new ParamError(t.getField(), t.getDefaultMessage()));
        });

        logger.error(String.format("[%s] , ip : {}", request.getRequestURI()),
                getIpAddress(), e);
        Response response = new Response(ResponseEnum.PARAM_ERROR.getCode(), ResponseEnum.PARAM_ERROR.getMsg(), errors);
        logger.error("响应结果:{}", JSONUtils.toJson(response));
        return response;
    }

    private String getIpAddress() {
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
